<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8"/>
    <title>文件上传页面</title>
</head>
<body>
<h1>文件上传页面</h1>
<div class="box">
    <input type="file" name="files" multiple="multiple" id="files">
    <a href="javascript:void(0)" class="btn" onclick="fileUpload()">上传文件</a>
    <div id="info" style="margin-top: 50px"></div>
    <div id="speed" style="margin-top: 50px"></div>
</div>
</body>
<script type="text/javascript">
    function $(id) {
        return document.getElementById(id);
    }

    function fileUpload() {
        //如何通过js获取文件列表进行上传
        var formDate = new FormData();
        var files = $("files").files;
        for (var i = 0; i < files.length; i++) {
            formDate.append("files", files[i]);
        }
        //创建ajax的核心对象，使用原生ajax
        var xhr = new XMLHttpRequest();
        var oldLoaded = 0, curLoaded = 0, total = 0;//上一秒的数据
        //添加进度监听器
        xhr.upload.addEventListener("progress", function (event) {
            $("info").innerHTML = "已经上传：" + getM(event.loaded) + "M/" + getM(event.total) + "M  " + "百分比:" + Math.round(event.loaded / event.total * 100) + "%";
            curLoaded = event.loaded;
            if (oldLoaded == 0) {
                oldLoaded = event.loaded;
                total = event.total;
            }
        }, false);
        //定时器，用来计算速度
        var sppdInterval = setInterval(function () {
            var mult = curLoaded - oldLoaded;//一秒发生了什么事情
            mult *= 4;
            var leave = total - curLoaded;//剩余多少
            oldLoaded = curLoaded;//将这一秒的赋值给上一秒的值
            $("speed").innerHTML = getM(mult) + "m/s";
            $("speed").innerHTML += " 剩余" + Math.round(leave / mult) + "s";
            if (leave <= 0) {
                clearInterval(sppdInterval)
            }
        }, 250);
        //指定提交方式以及方式
        xhr.open("post", "upload", true);
        //将文件列表放进去
        xhr.send(formDate);
    }

    //字节转换成兆
    function getM(length) {
        return Math.round(length / (1024 * 1024) * 100) / 100.0;
    }
</script>
</html>